﻿@*
//------------------------------------------------------------------------------
//  此代码版权声明为全文件覆盖，如有原作者特别声明，会在下方手动补充
//  此代码版权（除特别声明外的代码）归作者本人Diego所有
//  源代码使用协议遵循本仓库的开源协议及附加协议
//  Gitee源代码仓库：https://gitee.com/diego2098/ThingsGateway
//  Github源代码仓库：https://github.com/kimdiego2098/ThingsGateway
//  使用文档：https://diego2098.gitee.io/thingsgateway-docs/
//  QQ群：605534569
//------------------------------------------------------------------------------
*@

@page "/gatewayconfig/uploaddevice"
@namespace ThingsGateway.Gateway.Blazor
@using System.Linq.Expressions;
@using BlazorComponent;
@using Furion;
@using Mapster;
@using Masa.Blazor.Presets;
@using System.IO;
@using Masa.Blazor;
@using Microsoft.AspNetCore.Authorization;

@using ThingsGateway.Admin.Blazor;
@using ThingsGateway.Admin.Core;

@attribute [Authorize]
@inherits BaseComponentBase
@inject UserResoures UserResoures
@layout MainLayout
@if (IsMobile)
{
    @GetAppDataTable()
}
else
{
    <MRow>
        <MCol Md=2 Cols="12">
            <MCard Class="ma-2" Height=@("100%")>
                <MCardTitle>
                    <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="mx-2 my-1" @bind-Value="_searchName"
                                Outlined Label=@typeof(CollectDevice).GetDescription(nameof(CollectDevice.DeviceGroup)) />
                </MCardTitle>
                <MTreeview Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight+100}px);overflow-y:auto")
                          Dense TItem="string" TKey="string" ActiveChanged=@(async a=>
                       {
                       if(search.DeviceGroup!=a.FirstOrDefault())
                       {
                       search.DeviceGroup=a.FirstOrDefault();
                       await DatatableQuery();
                       }
                       } )
                           Items="_deviceGroups" ItemText="r=>r" ItemChildren="r=>null"
                           Search="@_searchName"
                          Activatable ItemKey=@(r=>r)>
                    <LabelContent>
                        <span title=@context.Item>
                            @context.Item
                        </span>
                    </LabelContent>
                </MTreeview>
            </MCard>
        </MCol>
        <MCol Md=10 Cols="12">

            @GetAppDataTable( )

        </MCol>
    </MRow>
}
<ImportExcel @ref=ImportExcel Import="SaveDeviceImportAsync" Preview="DeviceImportAsync" />



@code {
    RenderFragment GetAppDataTable()
    {
        RenderFragment renderFragment =
    @<AppDataTable @ref="_datatable" TItem="UploadDevice" SearchItem="UploadDevicePageInput"
                           StyleString=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight+10}px)")
                       AddItem="UploadDeviceAddInput" EditItem="UploadDeviceEditInput" DescFunc=@(memberInfo=>memberInfo.GetCustomAttribute<SqlSugar.SugarColumn>(true)?.ColumnDescription)
                           IsMenuOperTemplate=false SearchModel="search"
                           QueryCallAsync="QueryCallAsync" AddCallAsync="AddCallAsync"
                           EditCallAsync="EditCallAsync" DeleteCallAsync="DeleteCallAsync"
                                          IsShowDetailButton
                                          IsShowQueryButton
                           IsShowAddButton=@UserResoures.IsHasButtonWithRole("gatewayuploaddeviceadd")
                           IsShowDeleteButton=@UserResoures.IsHasButtonWithRole("gatewayuploaddevicedelete")
                           IsShowEditButton=@UserResoures.IsHasButtonWithRole("gatewayuploaddeviceedit")>
        <SearchTemplate>
            <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.Name" Clearable
                                Outlined Label=@context.Description(x => x.Name) />
            <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.PluginName" Clearable
                                Outlined Label=@context.Description(x => x.PluginName) />
        </SearchTemplate>
        <OtherToolbarTemplate>
            <MMenu OffsetY Context="menu">
                <ActivatorContent>
                    <MButton @attributes="@menu.Attrs" Color="primary"
                             Class="my-1  mx-2 ">
                        复制
                        <AppChevronDown></AppChevronDown>
                    </MButton>
                </ActivatorContent>
                <ChildContent>
                    <MList>
                        <MListItem OnClick="()=>CopyDevice(context)"> 复制设备 </MListItem>
                    </MList>

                </ChildContent>
            </MMenu>
            <MMenu OffsetY Context="menu">
                <ActivatorContent>
                    <MButton @attributes="@menu.Attrs" Color="primary"
                             Class="my-1  mx-2 ">
                        导出
                        <AppChevronDown></AppChevronDown>
                    </MButton>
                </ActivatorContent>
                <ChildContent>
                    <MList>
                        <MListItem OnClick="()=>DownExportAsync()"> 导出全部</MListItem>
                        <MListItem OnClick="()=>DownExportAsync(search)">  导出搜索项 </MListItem>
                    </MList>

                </ChildContent>
            </MMenu>
            <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewayuploaddeviceedit")) Class="my-1  mx-2" OnClick="()=>{ ImportExcel.Step=1;  ImportExcel.IsShowImport=true;}" Color="primary">
                导入
            </MButton>
        </OtherToolbarTemplate>
        <AddTemplate>
            @GetRenderFragment(context)
        </AddTemplate>

        <EditTemplate>
            @GetRenderFragment(context)

        </EditTemplate>


        <ItemColTemplate>
            @switch (context.Header.Value)
            {

                case nameof(context.Item.Enable):
                    <EnableChip Value="context.Item.Enable">
                    </EnableChip>
                    break;
                case nameof(context.Item.PluginId):
                    <span title=@context.Value>
                        @(
                            App.GetService<DriverPluginService>().GetNameById(context.Item.PluginId)
                                )
                    </span>
                    break;
                default:
                    @if (context.Header.CellClass?.Contains("text-truncate") == true)
                    {
                        <span title=@context.Value>
                            @context.Value
                        </span>
                    }
                    else
                    {
                        @context.Value
                    }
                    break;


            }

        </ItemColTemplate>
    </AppDataTable>

    ;
        return renderFragment;
    }
    RenderFragment GetRenderFragment(UploadDeviceEditInput context)
    {
        RenderFragment renderFragment = null;
        renderFragment +=
    @<div>
        <MTabs @bind-Value="tab">
            <MTab Value="1" >   基本信息    </MTab>
            <MTab Value="2">    扩展属性     </MTab>
        </MTabs>

        <MTabsItems Value="tab">
            <MTabItem Value="1">
                <MCard Flat Class="ma-2">
                    <MSubheader Class="mt-4 font-weight-black"> @(context.Description(x => x.Name))  </MSubheader>
                    <MTextField Dense Outlined HideDetails="@("auto")" @bind-Value=@context.Name />

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.Description))  </MSubheader>
                    <MTextField Dense Outlined HideDetails="@("auto")" @bind-Value=@context.Description />

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.DeviceGroup))  </MSubheader>
                    <MTextField Dense Outlined HideDetails="@("auto")" @bind-Value=@context.DeviceGroup />


                    <MSubheader Class="mt-4 font-weight-black">    @(typeof(UploadDeviceRunTime).GetDescription(nameof(UploadDeviceRunTime.PluginName)))  </MSubheader>
                    <MCascader Value="context.PluginId" Class="mt-3 mr-3" Clearable TValue=long TItem="DriverPluginCategory"
                               ValueChanged=@(a=>DriverValueChangedAsync(context,a))
                               Items="DriverPlugins" ItemText="u => u.Name" ItemValue="u => u.Id" ItemChildren="u => u.Children"
                               MenuProps="@(props => { props.Auto = true; props.OffsetY = true; })"
                               ShowAllLevels="false" HideDetails="@("auto")" Height="30" Dense>
                    </MCascader>

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.Enable))  </MSubheader>
                    <MSwitch @bind-Value=@context.Enable />

                    <MSubheader Class="mt-4 font-weight-black">    @(context.Description(x => x.IsLogOut))  </MSubheader>
                    <MSwitch @bind-Value=@context.IsLogOut />

                </MCard>
            </MTabItem>
            <MTabItem Value="2">
                <MCard Flat Class="ma-2">
                    <MButton Class="my-3" OnClick=@(async() =>
                         {
                         if(context.PluginId>0)
                         {
                         context.DevicePropertys= GetDriverProperties(context.PluginId,context.Id);
                         }
                         else
                         {
                         await PopupService.EnqueueSnackbarAsync("需选择驱动",AlertTypes.Error);
                         }
                         }
                         ) Color="primary">
                        刷新设备属性
                    </MButton>
                    @if (context.DevicePropertys != null)
                    {
                        @foreach (var item in context.DevicePropertys)
                        {
                            <MSubheader Class="mt-4 font-weight-black"> @item.Description </MSubheader>
                            <MTooltip Disabled=item.Remark.IsNullOrEmpty() Bottom Context="tip">
                                    <ActivatorContent>
                                        @if (item.PropertyName.Contains("BigText"))
                                    {
                                        <MTextarea AutoGrow Dense @attributes="@tip.Attrs" Outlined HideDetails="@("auto")" @bind-Value=@item.Value />
                                    }
                                    else
                                    {
                                        <MTextField Type="@(item.PropertyName.Contains("Password") ? "password" : "text")" @attributes="@tip.Attrs" Dense Outlined HideDetails="@("auto")" @bind-Value=@item.Value />
                                    }
                                </ActivatorContent>
                                <ChildContent>
                                    <span>@item.Remark</span>
                                </ChildContent>
                            </MTooltip>
                        }

                    }
                </MCard>
            </MTabItem>
        </MTabsItems>
    </div>
    ;
        return renderFragment;
    }
}
